import { useEffect, useState } from 'react'
import {
  Button,
  Card,
  Col,
  Popconfirm,
  Row,
  Table,
} from 'antd';
import { Column } from './types';
import type { ColumnsType } from 'antd/es/table';
import '@/styles/app.scss';
import styles from '@/styles/baseHeader.module.scss';
import OperateHeaderForm from './components/OperateHeaderForm'

// mock数据
const defaultData: Column[] = [
  {
    "id": "code",
    "parentId": "-1",
    "children": null,
    "name": null,
    "level": 0,
    "title": "编号",
    "type": "FIXED",
  },
  {
    "id": "name",
    "parentId": "-1",
    "children": null,
    "name": null,
    "level": 0,
    "title": "名称",
    "type": "FIXED",
  },
  {
    "id": "remark",
    "parentId": "-1",
    "children": null,
    "name": null,
    "level": 0,
    "title": "工料概要说明",
    "type": "FIXED",
  },
]

// 类型
const filterType = [
  { key: 'CUSTOMIZE', value: '自定义列' },
  { key: 'FIXED', value: '固定列' },
  { key: 'REMARK', value: '备注列' },
  { key: 'USER_FILL', value: '用户手填列' },
];

// 获取最后一个符合条件的下表
function findLastIndex<T>(arr: T[], condition: (value: T, index: number, array: T[]) => boolean): number {
  let lastIndex = -1;
  for (let i = 0; i < arr.length; i++) {
    if (condition(arr[i], i, arr)) {
      lastIndex = i;
    }
  }
  return lastIndex;
}

function App() {
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [dataSource, setDataSource] = useState<Column[]>(defaultData);
  const [operateColumn, setOperateColumn] = useState<Column | null>(null);
  const [operateType, setOperateType] = useState('new');
  const [parentId, setParentId] = useState('');
  const columns: ColumnsType<Column> = [
    {
      title: '表头名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
    },
    {
      title: '列类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      render: (d: string) => {
        const typeItem = filterType.find(i => d === i.key);
        return (
          <span>{typeItem ? typeItem.value : '未知'}</span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      width: 360,
      render: (d: any, item: any) => {
        return (
          <div>
            <Button type="link" onClick={() => handleNewClomn(item)} disabled={item.type === 'FIXED'}>新建子集</Button>
            <Button type="link" onClick={() => handleEditClomn(item)}>编辑</Button>
            <Popconfirm title="确定删除?" onConfirm={() => handleDelClomn(d)}>
              <Button
                type="link"
                disabled={item.type === 'FIXED'}
                style={{ color: item.type === 'FIXED' ? '' : 'red' }}
              >删除</Button>
            </Popconfirm>
          </div>
        )
      },
    },
  ];

  useEffect(() => {
    // 获取表头列表
    setTimeout(() => {
      setLoading(false)
    }, 100);
  }, []);

  const initColumn = () => {
    setParentId('');
    setOperateType('new');
    setOperateColumn(null)
  }

  // 新建-右上角-最后一个系统默认固定列的前面
  const addRootColumn = (newColumn: Column) => {
    // lastFixedColumnIndex是最后一个固定列的索引
    const lastIndex = findLastIndex(dataSource, (item) => item.type === 'FIXED');
    newColumn && dataSource.splice(lastIndex, 0, newColumn);
  }

  // 新建-子集
  const addColumn = (columns: Column[], newColumn: Column, parentId: string) => {
    // 要求符合条件终止循环，所以此次不使用forEach
    for (const column of columns) {
      if (column.id === parentId) {
        if (!column.children) column.children = [];
        column.children.push(newColumn);
        return;
      }
      if (column.children) {
        addColumn(column.children, newColumn, parentId);
      }
    }
  }

  // 编辑-子集
  const editColumn = (columns: Column[], newColumn: Column) => {
    for (const column of columns) {
      if (column.id === newColumn.id) {
        column.type = newColumn.type;
        column.title = newColumn.title;
        return;
      };
      if (column.children) {
        editColumn(column.children, newColumn)
      }
    }
  }

  // 删除-子集
  const deleteColumn = (columns: Column[], id: string) => {
    for (let i = 0; i < columns.length; i++) {
      if (columns[i].id === id) {
        columns.splice(i, 1);
        return;
      }
      if (columns[i].children) {
        deleteColumn(columns[i].children, id);
      }
      if (columns[i].children && columns[i].children.length === 0) {
        columns[i].children = null
      }
    }
  }

  const handleNewClomn = (item?: Column) => {
    item?.id && setParentId(item.id);
    setOperateType('new');
    setModalVisible(true);
  }

  const handleEditClomn = (item: Column) => {
    setOperateColumn(item)
    setOperateType('edit');
    setModalVisible(true);
  }

  const handleDelClomn = (parentId: string) => {
    deleteColumn(dataSource, parentId)
    setDataSource([...dataSource]);
  }

  const handleOk = (newColumn: Column | null) => {
    if (operateType === 'edit') {
      newColumn && editColumn(dataSource, newColumn)
    } else if (operateType === 'new' && !parentId) {
      newColumn && addRootColumn(newColumn)
    } else {
      newColumn && addColumn(dataSource, newColumn, parentId)
    }
    setDataSource([...dataSource]);
    setModalVisible(false);
    initColumn();
  }

  const handleCancel = () => {
    setModalVisible(false);
    initColumn();
  }

  return (
    <>
      <Card
        title="编辑表头"
        bordered={false}
        className={styles.cardContain}
        styles={{
          body: {
            display: 'flex',
            flex: 1,
            flexDirection: 'column',
            overflowY: 'auto'
          }
        }}
      >
        <Row style={{ marginBottom: '10px' }}>
          <Col span={22}><b>表头</b></Col>
          <Col span={2}>
            <Button onClick={() => handleNewClomn()} style={{ fontWeight: '600' }}>新建</Button>
          </Col>
        </Row>
        <Table
          loading={loading}
          rowKey="id"
          dataSource={dataSource}
          columns={columns}
          pagination={{
            showSizeChanger: true,
            total: dataSource.length,
            defaultPageSize: 20,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          scroll={{ x: '100%' }}
        />
      </Card>
      {
        modalVisible && (
          <OperateHeaderForm
            column={operateColumn}
            onCancel={() => handleCancel()}
            onConfirm={(column) => handleOk(column)}
          />
        )
      }
    </>
  )
}

export default App
